// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-20

package elastic

import (
	"gitee.com/go-libs/config"
	"github.com/elastic/go-elasticsearch/v7"
	"sync"
)

type Config struct {
	cli *elasticsearch.Client
	err error
	mu  *sync.RWMutex

	Addresses  []string `yaml:"addresses"`
	Indexes    []string `yaml:"indexes"`
	IndexTypes []string `yaml:"index-types"`
	Timeout    int      `yaml:"timeout"`
	Username   string   `yaml:"username"`
	Password   string   `yaml:"password"`
}

func (o *Config) Client() (*elasticsearch.Client, error) {
	o.mu.Lock()
	defer o.mu.Unlock()

	if o.cli != nil {
		return o.cli, nil
	}

	cli, err := elasticsearch.NewClient(elasticsearch.Config{
		Addresses: o.Addresses,
		Username:  o.Username,
		Password:  o.Password,
	})

	if err != nil {
		return nil, err
	}

	o.cli = cli
	return cli, nil
}

func (o *Config) init() *Config {
	o.err = config.Seek("viewer.yaml", "viewer.yml").ScanYaml(o)
	o.mu = new(sync.RWMutex)
	return o
}
